// 该文件用于创建一个Vue中的路由器（router）

// 引入vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'
import { TK,  getUid, getToken, removeToken } from "@/common/const.js";
import { postCheckToken } from "@/network/login.js";

const Home = () => import('@/views/home/Home')
const Category = () => import('@/views/category/Category')
const Profile = () => import('@/views/profile/Profile')
const Shopcart = () => import('@/views/shopcart/Shopcart')
const Detail =() => import('@/views/detail/Detail')
const profile_uid =() => import("@/views/profile/Profile.vue")
const Login =() =>import("@/views/login/Login.vue")

// 安装插件
Vue.use(VueRouter)

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location)
}

// 创建一个路由器（router）用于管理整个vue项目中所有的路由（route）
const routes = [
    {
        path: '/',
        redirect: '/home'
    },
   {
    path:'/home', 
    component:Home
   },
   {
    path:'/category',
    component:Category
   },
   {
    path:'/profile',
    component:Profile,
    beforeEnter(to, from, next) {
      let uid = getUid();
      if (uid) {
        next("/profile/" + uid);
      } else {
        next("/login");
      }
    }
   },
   {
    path: "/profile/:uid",
    component: profile_uid,
    beforeEnter(to, from, next) {
      //1. 获取token
      let allToken = getToken();
      //2. 没有 token 就重新登录 (避免用户直接输入 uid进入此路由)
      if (allToken.token != null) {
        //发送网络请求，检验token
        routerCheckToken(allToken, next);
      } else {
        next("/login");
      }
    }
  },
   {
    path:'/shopcart',
    component:Shopcart
   },
   {
     path:'/detail/:iid',
     component:Detail
   },{
    path:'/login',
    component:Login
   }
]

const router  = new VueRouter({
    routes,
    mode:'hash',
})

function routerCheckToken(token, next) {
  postCheckToken(token)
    .then(res => {
      //3. 长期token过期 或 没有长期token且过期了
      if (res.isExpire == true) {
        console.log("重新登录");
        removeToken();
        next("/login");
      } else {
        //有newToken表示这是一个 长期token
        if (res.newToken != "") {
          localStorage.setItem(TK, res.newToken);
        } else {
          console.log("短期token没过期");
        }
        next();
      }
    })
    .catch(err => {
      console.log(err);
    });
}

// 导出router
export default router